﻿using BySoft.Server.Business;
using BySoft.Server.Business.UserCode;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;
using BySoft.Web.Utility;
using OneSoft.EntityCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BySoft.Web.Site.BOM
{
    public partial class BOMEdit : AuthBasePage
    {
        public DataTable BOMMaterialDT
        {
            set { Session["BOMMaterialDT"] = value; }
            get
            {
                if (Session["BOMMaterialDT"] == null)
                {
                    return CreateDt();
                }
                else
                {
                    return (DataTable)Session["BOMMaterialDT"];
                }
            }
        }
        public DataTable CreateDt()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("BOMDetailID");
            dt.Columns.Add("IsDirect");//是否直接材料
            dt.Columns.Add("IsDirectName");
            dt.Columns.Add("MaterialID");//原料编号
            dt.Columns.Add("MaterialName");//原料名称
            dt.Columns.Add("Specifications");//规格
            dt.Columns.Add("Unit");//单位
            dt.Columns.Add("Long");//长
            dt.Columns.Add("Width");//宽
            dt.Columns.Add("Height");//高
            dt.Columns.Add("OutSide");//外径
            dt.Columns.Add("InSide");//内径
            dt.Columns.Add("MMNumber");//单件毫米数
            dt.Columns.Add("SingleWeight");//单件重量
            dt.Columns.Add("SingleNum");//单件数量
            dt.Columns.Add("IsNew");
            dt.Columns.Add("IsDel");
            return dt;
        }

        public DataTable BOMKnifeDT
        {
            set { Session["BOMKnifeDT"] = value; }
            get
            {
                if (Session["BOMKnifeDT"] == null)
                {
                    return CreateKnifeDt();
                }
                else
                {
                    return (DataTable)Session["BOMKnifeDT"];
                }
            }
        }
        public DataTable CreateKnifeDt()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("BOMKnifeID");
            dt.Columns.Add("KnifeID");//刀具编号
            dt.Columns.Add("KnifeName");//刀具名称
            dt.Columns.Add("Specifications");//规格
            dt.Columns.Add("Nums");//数量
            dt.Columns.Add("KnifeStatus");//刀具状态
            dt.Columns.Add("IsNew");
            dt.Columns.Add("IsDel");
            return dt;
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BOMKnifeDT = null;
                BOMMaterialDT = null;
                InitData();
            }
            txtProductID.Attributes.Add("readonly", "true");
            txtProductName.Attributes.Add("readonly", "true");
            txtUnit.Attributes.Add("readonly", "true");
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.Page, "iframeAutoFit();");
        }

        private void InitData()
        {
            string id = HttpUtility.UrlDecode(UIHelper.GetQueryStringValue("id"));
            if (!string.IsNullOrEmpty(id))
            {
                DataTable dt = BsBOMBusiness.GetBOMDetailByID(id);
                if (dt != null && dt.Rows.Count > 0)
                {
                    DataRow d = dt.Rows[0];
                    lblBOMID.Text = CommonMethod.GetString(d["BOMID"]);
                    cpBillDate.Value = string.Format("{0:yyyy-MM-dd}", d["BillDate"]);
                    txtProductID.Text = CommonMethod.GetString(d["ProductID"]);
                    hdWorkOrderNo.Value = CommonMethod.GetString(d["WorkOrderNo"]);
                    txtProductName.Text = CommonMethod.GetString(d["ProductName"]);
                    txtUnit.Text = CommonMethod.GetString(d["Unit"]);
                    txtRemark.Text = CommonMethod.GetString(d["Remark"]);

                    DataTable dtemp = BOMMaterialDT.Copy();
                    foreach (DataRow dr in dt.Rows)
                    {
                        DataRow drow = dtemp.NewRow();
                        drow["BOMDetailID"] = CommonMethod.GetString(dr["BOMDetailID"]);
                        drow["MaterialID"] = CommonMethod.GetString(dr["MaterialID"]);
                        drow["MaterialName"] = CommonMethod.GetString(dr["MaterialName"]);
                        drow["Specifications"] = CommonMethod.GetString(dr["Specifications"]);
                        drow["Unit"] = CommonMethod.GetString(dr["Unit"]);
                        drow["IsDirect"] = CommonMethod.GetString(dr["IsDirect"]);
                        drow["IsDirectName"] = CommonMethod.GetString(dr["IsDirect"]) == "1" ? "是" : "否";
                        drow["Long"] = CommonMethod.GetString(dr["Long"]);
                        drow["Width"] = CommonMethod.GetString(dr["Width"]);
                        drow["Height"] = CommonMethod.GetString(dr["Height"]);
                        drow["OutSide"] = CommonMethod.GetString(dr["OutSide"]);
                        drow["InSide"] = CommonMethod.GetString(dr["InSide"]);
                        drow["MMNumber"] = CommonMethod.GetString(dr["MMNumber"]);
                        drow["SingleWeight"] = CommonMethod.GetString(dr["SingleWeight"]);
                        drow["SingleNum"] = CommonMethod.GetString(dr["SingleNum"]);
                        drow["IsDel"] = "-1";
                        drow["IsNew"] = "-1";
                        dtemp.Rows.Add(drow);
                    }
                    BOMMaterialDT = dtemp.Copy();
                }
                DataTable dtKnife = BsBOMBusiness.GetBOMKnifeByID(id);
                if (dtKnife != null && dtKnife.Rows.Count > 0)
                {
                    DataTable d = BOMKnifeDT.Copy();
                    foreach (DataRow dr in dtKnife.Rows)
                    {
                        DataRow drow = d.NewRow();
                        drow["BOMKnifeID"] = CommonMethod.GetString(dr["BOMKnifeID"]);
                        drow["KnifeID"] = CommonMethod.GetString(dr["KnifeID"]);
                        drow["KnifeName"] = CommonMethod.GetString(dr["KnifeName"]);
                        drow["Specifications"] = CommonMethod.GetString(dr["Specifications"]);
                        drow["Nums"] = CommonMethod.GetString(dr["Nums"]);
                        drow["KnifeStatus"] = CommonMethod.GetString(dr["KnifeStatus"]);
                        drow["IsDel"] = "-1";
                        drow["IsNew"] = "-1";
                        d.Rows.Add(drow);
                    }
                    BOMKnifeDT = d.Copy();
                }
            }
            BindMaterial();
            BindKnife();
        }

        private void BindMaterial()
        {
            DataView dv = new DataView(BOMMaterialDT);
            dv.RowFilter = " IsDel <> '1' ";
            DataTable dt = dv.ToTable();
            dt.Columns.Add("OrderNum");
            if (dt != null && dt.Rows.Count > 0)
            {
                int index = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    dr["OrderNum"] = index;
                    index++;
                }
                grdResult.DataSource = dt;
                grdResult.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(grdResult, dt);
            }
            UIHelper.RunScript(this.UpdatePanel4, "iframeAutoFit();");
        }

        private void BindKnife()
        {
            DataView dv = new DataView(BOMKnifeDT);
            dv.RowFilter = " IsDel <> '1' ";
            DataTable dt = dv.ToTable();
            dt.Columns.Add("OrderNum");
            if (dt != null && dt.Rows.Count > 0)
            {
                int index = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    dr["OrderNum"] = index;
                    index++;
                }
                grdKnife.DataSource = dt;
                grdKnife.DataBind();
            }
            else
            {
                UIHelper.BindEmptyGridView(grdKnife, dt);
            }
            UIHelper.RunScript(this.UpdatePanel2, "iframeAutoFit();");
        }

        private void AddMaterial()
        {
            BOMMaterialDT = GetAddMaterial(BOMMaterialDT).Copy();
        }

        private DataTable GetAddMaterial(DataTable dt)
        {
            DataTable dtTemp = dt.Copy();
            foreach (GridViewRow gvr in grdResult.Rows)
            {
                if (gvr.RowType == DataControlRowType.DataRow)
                {
                    Label lblBOMDetailID = gvr.FindControl("lblBOMDetailID") as Label;
                    Label lblMaterialID = gvr.FindControl("lblMaterialID") as Label;
                    Label lblMaterialName = gvr.FindControl("lblMaterialName") as Label;
                    Label lblSpecifications = gvr.FindControl("lblSpecifications") as Label;
                    Label lblUnit = gvr.FindControl("lblUnit") as Label;
                    Label lblIsDirect = gvr.FindControl("lblIsDirect") as Label;
                    Label lblIsDirectName = gvr.FindControl("lblIsDirectName") as Label;
                    Label lblLong = gvr.FindControl("lblLong") as Label;
                    Label lblWidth = gvr.FindControl("lblWidth") as Label;
                    Label lblHeight = gvr.FindControl("lblHeight") as Label;
                    Label lblOutSide = gvr.FindControl("lblOutSide") as Label;
                    Label lblInSide = gvr.FindControl("lblInSide") as Label;
                    TextBox txtMMNumber = gvr.FindControl("txtMMNumber") as TextBox;
                    TextBox txtSingleWeight = gvr.FindControl("txtSingleWeight") as TextBox;
                    TextBox txtSingleNum = gvr.FindControl("txtSingleNum") as TextBox;
                    string MaterialID = CommonMethod.GetString(lblMaterialID.Text);


                    DataRow[] drs = dtTemp.Select("MaterialID='" + MaterialID + "'");
                    if (drs.Length > 0)
                    {
                        drs[0]["BOMDetailID"] = GetGridViewString(lblBOMDetailID);
                        drs[0]["MaterialID"] = GetGridViewString(lblMaterialID);
                        drs[0]["MaterialName"] = GetGridViewString(lblMaterialName);
                        drs[0]["Specifications"] = GetGridViewString(lblSpecifications);
                        drs[0]["Unit"] = GetGridViewString(lblUnit);
                        drs[0]["IsDirect"] = GetGridViewString(lblIsDirect);
                        drs[0]["IsDirectName"] = GetGridViewString(lblIsDirectName);
                        drs[0]["Long"] = GetGridViewString(lblLong);
                        drs[0]["Width"] = GetGridViewString(lblWidth);
                        drs[0]["Height"] = GetGridViewString(lblHeight);
                        drs[0]["OutSide"] = GetGridViewString(lblOutSide);
                        drs[0]["InSide"] = GetGridViewString(lblInSide);
                        drs[0]["MMNumber"] = GetGridViewString(txtMMNumber);
                        drs[0]["SingleWeight"] = GetGridViewString(txtSingleWeight);
                        drs[0]["SingleNum"] = GetGridViewString(txtSingleNum);
                    }
                }
            }
            return dtTemp;
        }

        private void AddKnife()
        {
            BOMKnifeDT = GetAddKnife(BOMKnifeDT).Copy();
        }

        private DataTable GetAddKnife(DataTable dt)
        {
            DataTable dtTemp = dt.Copy();
            foreach (GridViewRow gvr in grdKnife.Rows)
            {
                if (gvr.RowType == DataControlRowType.DataRow)
                {
                    Label lblBOMKnifeID = gvr.FindControl("lblBOMKnifeID") as Label;
                    Label lblKnifeID = gvr.FindControl("lblKnifeID") as Label;
                    Label lblKnifeName = gvr.FindControl("lblKnifeName") as Label;
                    Label lblSpecifications = gvr.FindControl("lblSpecifications") as Label;
                    TextBox txtNums = gvr.FindControl("txtNums") as TextBox;
                    DropDownList ddlKnifeStatus = gvr.FindControl("ddlKnifeStatus") as DropDownList;
                    string KnifeID = CommonMethod.GetString(lblKnifeID.Text);


                    DataRow[] drs = dtTemp.Select("KnifeID='" + KnifeID + "'");
                    if (drs.Length > 0)
                    {
                        drs[0]["BOMKnifeID"] = GetGridViewString(lblBOMKnifeID);
                        drs[0]["KnifeID"] = GetGridViewString(lblKnifeID);
                        drs[0]["KnifeName"] = GetGridViewString(lblKnifeName);
                        drs[0]["Specifications"] = GetGridViewString(lblSpecifications);
                        drs[0]["Nums"] = GetGridViewString(txtNums);
                        drs[0]["KnifeStatus"] = GetGridViewString(ddlKnifeStatus);
                    }
                }
            }
            return dtTemp;
        }

        protected void btnKnifeHidden_Click(object sender, EventArgs e)
        {
            AddKnife();
            BindKnife();
        }

        protected void btnHidden_Click(object sender, EventArgs e)
        {
            AddMaterial();
            BindMaterial();
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete + "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
            }
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            string[] strs = strCode.Split(',');
            switch (e.CommandName)
            {
                case "del":
                    AddMaterial();
                    DataTable dt = BOMMaterialDT.Copy();
                    DataRow[] dr = dt.Select("MaterialID='" + strCode.Trim() + "'");
                    if (dr != null && dr.Length > 0)
                    {
                        dr[0]["IsDel"] = "1";
                    }
                    BOMMaterialDT = dt.Copy();
                    BindMaterial();
                    UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
                    break;
                default:
                    break;
            }
        }

        protected void grdKnife_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete + "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
                DropDownList ddlKnifeStatus = (DropDownList)e.Row.FindControl("ddlKnifeStatus");
                BindParameterForListControl("KnifeStatus", ddlKnifeStatus);
                UIHelper.InsertFirstItem(ddlKnifeStatus);
                string KnifeStatus = ((DataTable)((GridView)sender).DataSource).Rows[e.Row.RowIndex]["KnifeStatus"].ToString().Trim();
                if (!string.IsNullOrEmpty(KnifeStatus))
                {
                    ddlKnifeStatus.SelectedValue = KnifeStatus;
                }
            }
        }

        protected void grdKnife_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            string[] strs = strCode.Split(',');
            switch (e.CommandName)
            {
                case "del":
                    AddKnife();
                    DataTable dt = BOMKnifeDT.Copy();
                    DataRow[] dr = dt.Select("KnifeID='" + strCode.Trim() + "'");
                    if (dr != null && dr.Length > 0)
                    {
                        dr[0]["IsDel"] = "1";
                    }
                    BOMKnifeDT = dt.Copy();
                    BindKnife();
                    UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
                    break;
                default:
                    break;
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }
            try
            {
                if (string.IsNullOrEmpty(CurrentUser.UserID))
                {
                    UIHelper.AlertMessage(this.Page, "等待时间太久，请重新填写！");
                    return;
                }
                if (!string.IsNullOrEmpty(this.lblBOMID.Text.Trim()))
                {
                    BsBomEntity entity = new BsBomEntity();
                    entity.BOMID = GetString(lblBOMID);
                    entity.BillDate = GetDateTime(cpBillDate);
                    entity.WorkOrderNo = GetString(hdWorkOrderNo);
                    entity.ProductID = GetString(txtProductID);
                    entity.Remark = GetString(txtRemark);
                    entity.ModifyDate = DateTime.Now;
                    entity.ModifyUserID = CurrentUser.UserID;
                    entity.ModifyUserName = CurrentUser.UserName;


                    if (BsBOMBusiness.SaveOrUpdate(entity, BOMMaterialDT, BOMKnifeDT, "Update"))
                    {
                        base.LogAction(BaseEnum.ActionType.Modify, entity.BOMID, true, null, new EntityBase[] { entity });
                        UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../BOM/BOMList.aspx");
                    }
                    else
                    {
                        UIHelper.AlertMessage(this.Page, Message.SaveFail);
                    }
                }
            }
            catch (Exception ex)
            {
                UIHelper.AlertMessage(this.Page, FomatString(ex.Message.ToString()));
            }
        }

        private bool ValidateData()
        {
            AddMaterial();
            DataView dv = new DataView(BOMMaterialDT);
            dv.RowFilter = " IsDel <> '1' ";
            DataTable dt = dv.ToTable();
            if (dt == null || dt.Rows.Count <= 0)
            {
                UIHelper.AlertMessage(this.Page, "请添加原料明细！");
                return false;
            }

            AddKnife();
            DataView dvc = new DataView(BOMKnifeDT);
            dvc.RowFilter = " IsDel <> '1' ";
            DataTable dtc = dvc.ToTable();
            if (dtc == null || dtc.Rows.Count <= 0)
            {
                UIHelper.AlertMessage(this.Page, "请添加刀具明细！");
                return false;
            }
            return true;
        }

    }
}